<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\CsMaterielCategoryTable;
use App\Http\Models\Mysql\CsMinorCategoryTable;
use App\Http\Models\Mysql\MaterielCategoryTable;
use App\Http\Models\Mysql\MaterielTable;
use App\Http\Models\Mysql\SsyAllocationIpurchaseListTable;
use App\Http\Models\Mysql\SsyAllocationIpurchaseTable;
use App\Http\Models\Mysql\SsyAllocationOrderListTable;
use App\Http\Models\Mysql\SsyAllocationOrderReturnTable;
use App\Http\Models\Mysql\SsyAllocationOrderTable;
use App\Http\Models\Mysql\SsyAllocationSaleListTable;
use App\Http\Models\Mysql\SsyAllocationSaleTable;
use App\Http\Models\Mysql\SsyJstPurchaseinOrderEmbroideryCountTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsyMaterialImagesTable;
use App\Http\Models\Mysql\SsyNewProductProcessSheetTable;
use App\Http\Models\Mysql\SsyNewProductsSizeTable;
use App\Http\Models\Mysql\SsyNewProductsTable;
use App\Http\Models\Mysql\SsyPricingExamineTable;
use App\Http\Models\Mysql\SsyProcessingFactoryNameTable;
use App\Http\Models\Mysql\SsyProcessingListDetailsDeliveryLogBakTable;
use App\Http\Models\Mysql\SsyProcessingListDetailsDeliveryLogTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\SsyReconciliationOrderTable;
use App\Http\Models\Mysql\SsyStyleImagesTable;
use App\Http\Models\Mysql\StyleBomColourConfigTable;
use App\Http\Models\Mysql\StyleBomSizeConfigTable;
use App\Http\Models\Mysql\StyleBomTable;
use App\Http\Models\Mysql\StyleColourTable;
use App\Http\Models\Mysql\StyleSizeTable;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Models\Mysql\SupplierCategoryTable;
use App\Http\Models\Mysql\SupplierContactTable;
use App\Http\Models\Mysql\SupplierTable;
use App\Http\Models\Mysql\UnitTable;
use App\Http\Models\Mysql\VerifyPriceTable;
use App\Http\Repository\CommonRepository;
use App\Http\Repository\LinmaoRepository;
use App\Http\Services\Op\LendService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:test {--type=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    protected $_cellName = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF',
        "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN"];

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $type = $this->option("type") ?? "";
        switch ($type){
            case "recontiliation":
                $this->exportReconciliation();
                break;
            case "supplier":
                $this->supplier();
                break;
            case "materiel":
                $this->materiel();
                break;
            case "excelImg":
                $this->excelImg();
                break;
            case 'pullMaterielLM':
                $this->pullMaterielLM();
                break;
            case 'pullStyleNoLM':
                $this->pullStyleNoLM();
                break;
            case 'pullStyleMaterielLM':
                $this->pullStyleMaterielLM();
                break;
            case "syncDelivery":
                $this->syncDelivery();
                break;
            case "optimizeGY":
                $this->optimizeGY();
                break;
            case "optimizeSize":
                $this->optimizeSize();
                break;
            case "updateContractDate":
                $this->updateContractDate();
                break;
        }
    }

    //图片写入单元格
    public function excelImg()
    {
        $filename = "demo(插入图片).xls";
        $file = storage_path("cache/").$filename;
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        $img = "http://cdn.13yu.com/style/undefined_153409.png";
        $cellCoordinate = 'B2'; // 目标单元格

        // 1. 设置B列的宽度为50px（影响该列所有单元格，包括B2）
        $sheet->getColumnDimension('B')->setWidth(6);
        // 2. 设置第2行的高度为50px（影响该行所有单元格，包括B2）
        // 注意：行高的像素换算需要通过公式计算（1像素 ≈ 0.75磅）
        $rowHeightInPoints = 50 * 0.75; // 50px ≈ 37.5磅
        $sheet->getRowDimension(2)->setRowHeight($rowHeightInPoints);

        try {
            // 3. 下载远程图片（获取二进制内容）
            // 注意：需确保PHP配置允许file_get_contents访问URL（allow_url_fopen=On）
            $imageContent = file_get_contents($img);
            if ($imageContent === false) {
                throw new Exception("无法下载远程图片: $img");
            }
            // 4. 将图片内容写入临时文件（PhpSpreadsheet需要文件路径）
            $tempFilePath = tempnam(sys_get_temp_dir(), 'img_') . '.png'; // 临时文件路径
            file_put_contents($tempFilePath, $imageContent);
            // 5. 创建图片对象并设置属性
            $drawing = new Drawing();
            $drawing->setPath($tempFilePath); // 设置图片路径
            $drawing->setCoordinates($cellCoordinate); // 指定单元格
            $drawing->setWidth(50); // 设置图片宽度（高度会按比例自动调整）
            $drawing->setHeight(50); // 如需固定高度，可取消注释
            // 6. 将图片插入工作表
            $drawing->setWorksheet($sheet);

            // 7. 保存Excel文件
            (new Xlsx($spreadsheet))->save($file);
            echo "已写入\n";
        } catch (\Exception $e) {
            echo "错误：" . $e->getMessage();
        } finally {
            // 清理临时文件
            if (isset($tempFilePath) && file_exists($tempFilePath)) {
                unlink($tempFilePath);
                echo "清除临时文件, $tempFilePath\n";
            }else{
                echo "未发现临时文件, $tempFilePath\n";
            }
        }
    }

    //数加物料供应商
    public function supplier()
    {
        $list = (new SupplierTable())->where('state', 0)->get()->toArray();
        foreach ($list as $item){
            $exist = (new SupplierCategoryTable())->where('supplier_id', $item['id'])->where('supplier_major_category_id', 1)->exists();
            if(!$exist){
                continue;
            }
            $contractObj = (new SupplierContactTable())->where('supplier_id', $item['id'])->first();
            $contractObj = empty($contractObj) ? [] : $contractObj->toArray();
            $data = [
                'supplier_id' => 'WL'.$item['id'],
                'factory_name' => $item['name'],
                'factory_name_jiancheng' => $item['short_name'],
                'group' => 8,
                'group_name' => '物料厂',
                'status' => 0,
                'type' => 0,
                'legal_person' => $contractObj['name'] ?? "",
                'contact_phone' => $contractObj['phone'] ?? "",
                'contact_address' => $contractObj['address'] ?? ""
            ];
            (new SsyProcessingFactoryNameTable())->createData($data);
        }
    }

    //物料档案数据优化
    public function materiel()
    {
        $materielList = (new MaterielTable())->orderBy('id', 'asc')->get(['id', 'number'])->toArray();
        $total = count($materielList);
        foreach ($materielList as $i => $item){
            echo "正在执行: [$total, ".($i+1)."], ";
            $csMaterielCategory = (new CsMaterielCategoryTable())->where('materiel_id', $item['id'])->get(['materiel_minor_category_id'])->toArray();
            if(empty($csMaterielCategory)){
                echo "未找到档案分类ID\n";
                continue;
            }
            $csMinorCategory = (new CsMinorCategoryTable())->where('id', $csMaterielCategory[0]['materiel_minor_category_id'])
                ->first(['materiel_major_category_id', 'name']);
            if(empty($csMinorCategory)){
                echo "未找到档案分类明细\n";
                continue;
            }
            $csMinorCategory = $csMinorCategory->toArray();
            $materielCategoryObj = (new MaterielCategoryTable())->where('materiel_major_category_id', $csMinorCategory['materiel_major_category_id'])
                ->where('name', $csMinorCategory['name'])->first(['id']);
            if(empty($materielCategoryObj)){
                echo "重新分类失败：未找到最新档案分类\n";
                continue;
            }
            (new MaterielTable())->updateData($item['id'], ['materiel_category_id' => $materielCategoryObj['id']]);
            echo "重新分类：成功\n";
        }
    }

    //导出调拨数据
    public function exportLends()
    {
        $filename = "借出明细.xls";
        $file = storage_path("cache/").$filename;
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        $header = [
            ['allocation_number','单号'],
            ['adduser','发起人'],
            ['groups','单据类型'],
            ['sku_code','sku编码'],
            ['type_name','款名'],
            ['sku_num','sku实际借出数'],
            ['sku_return_num', 'sku归还数'],
            ['sku_ipurchase_num', 'sku转内购数'],
            ['sku_give_num', 'sku转赠送数'],
            ['sku_sale_num', 'sku转销售数'],
            ['is_return','sku归还状态'],
            ['status','调拨状态'],
            ['reason','申请事由'],
            ['remark','备注'],
            ['createtime','发起时间'],
            ['source_allocation_number','来源单号'],
            ['is_subject', '主体']
        ];
        foreach($header as $index => $item){
            $sheet->setCellValue($this->_cellName[$index]."1", $item[1]);
            $sheet->getStyle($this->_cellName[$index]."1")->applyFromArray([
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => [
                        'argb' => Color::COLOR_BLACK,
                    ],
                ],
                'font' => [
                    'color' => [
                        'argb' => Color::COLOR_WHITE,
                    ],
                ]
            ]);
            $sheet->getColumnDimension($this->_cellName[$index])->setWidth('20');
        }
        $isSubjects = [
            "kz" => "十三余",
            "mz" => "妙哉",
//            "yx" => "有香",
//            'xm' => "一弦一木",
//            'js' => '锦瑟'
        ];
        $conn = DB::table("ssy_allocation_order_list as l")
            ->rightJoin("ssy_allocation_order as o", 'l.allocation_number', '=', 'o.allocation_number')
            ->select(["l.allocation_number as allocation_number","l.createtime as createtime","l.adduser as adduser","l.ourier_number as ourier_number",
                "l.reason as reason","l.remark as remark","l.data_status as data_status","l.status as status","l.source_allocation_number as source_allocation_number",
                "l.groups as groups","l.is_subject as is_subject","o.num as num","o.sku_code as sku_code","o.type_name as type_name","o.is_return as is_return",
                "l.data_return as data_return"]);
        $conn = $conn->whereIn('l.is_subject', array_keys($isSubjects))->whereIn('l.groups', [2, 3])->where('l.status', 1)
            ->where('l.data_status', 0)
            ->where('l.createtime', '<=', '2024-12-31 23:59:59');
        $allocationList = $conn->orderBy("l.createtime", "desc")->get()->toArray();
        $total = count($allocationList);
        $allocationMap = [];
        $num = 2;
        foreach ($allocationList as $aIndex => $item){
            echo "[$total, ".($aIndex+1)."], 正在写入....\n";
            $item = (Array)$item;
            $allocationNumber = $item['allocation_number'];
            if(!isset($allocationMap[$allocationNumber])){
                //计划数量
                $planNum = (new SsyAllocationOrderTable())->where('allocation_number', $allocationNumber)->sum('num');
                //实际数量
                $actuallyNum = (new SsyAllocationOrderReturnTable())->where('allocation_number', $allocationNumber)->where('transfer_type', 1)->sum("sj_num");
                //获取所有子调拨单
                $allocationReturnOrders = (new SsyAllocationOrderListTable())->where('source_allocation_number', $allocationNumber)->where('status', 1)
                    ->get(['allocation_number'])->toArray();
                $allocationReturnNums = array_column($allocationReturnOrders,'allocation_number');
                //实际归还数量
                $actuallyReturnNum = (new SsyAllocationOrderReturnTable())->whereIn('allocation_number', $allocationReturnNums)->where('transfer_type', 1)
                    ->sum('sj_num');
                //转内购数
                $ipurchaseList = (new SsyAllocationIpurchaseListTable())->where('jc_number', $allocationNumber)->where('status', 1)
                    ->get(['allocation_number'])->toArray();
                $allocationIpurchaseNums = array_column($ipurchaseList, 'allocation_number');
                $ipurchaseNum = (new SsyAllocationIpurchaseTable())->whereIn('allocation_number', $allocationIpurchaseNums)->sum('num');
                //转赠送数
                $allocationGiveOrders = (new SsyAllocationOrderListTable())->where('source_allocation_number', $allocationNumber)->where('status', 1)
                    ->where('groups', 1)->get(['allocation_number'])->toArray();
                $allocationGiveNums = array_column($allocationGiveOrders,'allocation_number');
                $giveNum = (new SsyAllocationOrderTable())->whereIn('allocation_number', $allocationGiveNums)->sum('num');
                //转销售
                $saleOrders = (new SsyAllocationSaleTable())->where('source_allocation_number', $allocationNumber)->get(['allocation_number', 'num'])->toArray();
                $saleNum = 0;
                $allocationSaleNums = array_column($saleOrders, 'allocation_number');
                if(!empty($allocationSaleNums)){
                    $saleList = (new SsyAllocationSaleListTable())->whereIn('allocation_number', $allocationSaleNums)->where('status', 1)
                        ->get(["allocation_number"])->toArray();
                    $allocationSaleValidNums = array_column($saleList, 'allocation_number');
                    foreach ($saleOrders as $saleItem){
                        if(in_array($saleItem['allocation_number'], $allocationSaleValidNums)){
                            $saleNum += $saleItem['num'];
                        }
                    }
                }
                $skuMap = [];
                if($item['groups'] == 2){
                    $details = (new LendService())->lendList($allocationNumber);
                }elseif ($item['groups'] ==1){
                    $details = (new LendService())->giveList($allocationNumber);
                }else{
                    $details = (new LendService())->returnList($allocationNumber, 3);
                }
                $skuMap = array_column($details, null, "sku_code");
                $allocationMap[$allocationNumber] = [
                    'plan_num' => $planNum,
                    'actually_num' => $actuallyNum ?:
                        ($item['status'] == 1 && str_starts_with($allocationNumber, "JZS") ? $planNum : 0),//借转送，无需推巨沃调拨计划，审核通过后为实际数,
                    'actually_return_num' => $actuallyReturnNum ?:
                        ($item['groups'] == 3 ? $actuallyNum : 0),//归还业务，实际数就是实际归还数,
                    'ipurchase_num' => $ipurchaseNum,
                    'give_num' => $giveNum,
                    'sale_num' => $saleNum,
                    'sku_details' => $skuMap
                ];
            }
            $status = $item['status'] == '0' ? "审核中" : ($item['status'] == '1' ? "通过" : $item['status']);
            $data = [
                'allocation_number' => $allocationNumber,
                'adduser' => $item['adduser'],
                'groups' => $item['groups'] == 1 ? "赠送" : ($item['groups'] == 2 ? "借出" : "归还"),
                'total_num' => $allocationMap[$allocationNumber]['plan_num']."/".$allocationMap[$allocationNumber]['actually_num'],
                'actually_return_num' => $allocationMap[$allocationNumber]['actually_return_num'],
                'ipurchase_num' => $allocationMap[$allocationNumber]['ipurchase_num'],
                'give_num' => $allocationMap[$allocationNumber]['give_num'],
                'sale_num' => $allocationMap[$allocationNumber]['sale_num'],
                'sku_code' => $item['sku_code'],
                'type_name' => $item['type_name'],
                'sku_num' => ($allocationMap[$allocationNumber]['sku_details'][$item['sku_code']]['actually_num'] ?? 0),
                'sku_return_num' => $item['groups'] == 3 ? ($allocationMap[$allocationNumber]['sku_details'][$item['sku_code']]['actually_num'] ?? 0)
                    : ($allocationMap[$allocationNumber]['sku_details'][$item['sku_code']]['actually_return_num'] ?? 0),//归还的实际调拨数就是 实际归还数
                'sku_ipurchase_num' => $allocationMap[$allocationNumber]['sku_details'][$item['sku_code']]['ipurchase_num'] ?? 0,
                'sku_give_num' => $allocationMap[$allocationNumber]['sku_details'][$item['sku_code']]['give_num'] ?? 0,
                'sku_sale_num' => $allocationMap[$allocationNumber]['sku_details'][$item['sku_code']]['sale_num'] ?? 0,
                'status' => $status,
                'is_return' => $item['is_return'] == 0 ? "未归还" : ($item['is_return'] == 1 ? "部分归还" : "全部归还"),
                'reason' => $item['reason'],
                'remark' => $item['remark'],
                'data_return' => $item['data_return'] == 0 ? "未归还" : ($item['data_return'] == 1 ? "部分归还" : "全部归还"),
                'data_status' => $item['data_status'] == 0 ? "正常" : "关闭",
                'createtime' => $item['createtime'],
                'is_subject' => $isSubjects[$item['is_subject']] ?? $item['is_subject'],
                'source_allocation_number' => $item['source_allocation_number'] ?: ""
            ];
            if(empty($data['sku_num'])){
                continue;
            }
            foreach ($header as $index => $hItem){
                $sheet->setCellValue($this->_cellName[$index].$num, $data[$hItem[0]]);
            }
            $num++;
        }
        // 保存Excel文件
        (new Xlsx($spreadsheet))->save($file);
        dd("数据下载完成！！！");
    }

    //导出款号数据
    public function exportStyle()
    {
        $year = $this->option("year") ?? "2024";
        $filename = "设计档案_有香_{$year}.xls";
        $file = storage_path("cache/").$filename;
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        $header = [
            ['number','款号'],
            ['name', '款名'],
            ['creator','创建人'],
            ['new_date','上新月份'],
            ['style_img','款式图片']
        ];
        foreach($header as $index => $item){
            $sheet->setCellValue($this->_cellName[$index]."1", $item[1]);
            $sheet->getStyle($this->_cellName[$index]."1")->applyFromArray([
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => [
                        'argb' => Color::COLOR_BLACK,
                    ],
                ],
                'font' => [
                    'color' => [
                        'argb' => Color::COLOR_WHITE,
                    ],
                ]
            ]);
            $sheet->getColumnDimension($this->_cellName[$index])->setWidth('20');
        }
        $numIndex = 2;
        $list = (new StyleTable())->where('approval_state', '<>', 4)->where('year', $year)->where('brand_id', 2)
            ->orderBy("year", "desc")->orderBy("month", "desc")->orderBy("creation_time", "desc")->get(['id', 'number', 'name', 'creator', 'year', 'month'])->toArray();
        $total = count($list);
        foreach ($list as $sIndex => $style){
            echo "正在写入: {$year}年上新 [{$total}, ".($sIndex+1)."] {$style['number']} \n";
            $styleImgObj = (new SsyStyleImagesTable())->where('type_no', $style['number'])->first();
            $styleImg = $styleImgObj->images ?? "";
            $data = [
                'number' => $style['number'],
                'name' => $style['name'],
                'creator' => $style['creator'],
                'new_date' => $style['year']."-".$style['month'],
                'style_img' => $styleImg,
            ];
            foreach ($header as $hIndex => $hItem){
                $sheet->setCellValue($this->_cellName[$hIndex].$numIndex, $data[$hItem[0]]);
                if($hItem[0] == 'color_value' && !empty($data[$hItem[0]])){
                    $sheet->getStyle($this->_cellName[$hIndex].$numIndex)->applyFromArray([
                        'fill' => [
                            'fillType' => Fill::FILL_SOLID,
                            'startColor' => [
                                'argb' => str_replace("#", "", $data['color_code']),
                            ],
                        ],
                    ]);
                }
            }
            $numIndex++;
        }
        // 保存Excel文件
        (new Xlsx($spreadsheet))->save($file);
        die("处理结束！！！");
    }

    //导出对账单明细
    public function exportReconciliation()
    {
        $filename = "对账单明细1_9月.xls";
        $file = storage_path("cache/").$filename;
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        $header = [
            ['brand_name','品牌'],
            ['recon_time', '对账日期'],
            ['factory_nmae','工厂名称'],
            ['type', '对账单类型'],
            ['purchasein_amount', '总货款金额'],
            ['additional_amount', '总额外费用'],
            ['fine_amount', '总违约赔偿'],
            ['kaip_amount', '总开票金额'],
            ['pay_amount', '总应付金额'],
            ['remark', '备注'],
            ['processing_code', '加工单'],
            ['type_no', '款号'],
            ['type_name', '款名'],
            ['totalnum', '回货数量'],
            ['pay_machining_price', '实付单价（绣花）'],
            ['total_cost_amount', '货款金额（绣花）'],
            ['emb_billing_amount', '开票金额（绣花）'],
            ['pay_price', '实付单价（成衣）'],
            ['cost_amount', '货款金额（成衣）'],
            ['billing_amount', '开票金额（成衣）'],
            ['verify_price_number', '核价单编码'],
            ['f69', '主料总价'],
            ['f70', '辅料总价'],
            ['f71', '包材总价'],
            ['f72', '加工费总价'],
            ['f77', '绣花费总价'],
            ['f78', '预估总价'],
            ['f61', '管理费率'],
            ['f62', '绣花成本总价'],
            ['f63', '绣花成本加价总价'],
            ['f64', '成衣成本总价'],
            ['f65', '成衣成本加价总价'],
        ];
        foreach($header as $index => $item){
            $sheet->setCellValue($this->_cellName[$index]."1", $item[1]);
            $sheet->getStyle($this->_cellName[$index]."1")->applyFromArray([
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => [
                        'argb' => Color::COLOR_BLACK,
                    ],
                ],
                'font' => [
                    'color' => [
                        'argb' => Color::COLOR_WHITE,
                    ],
                ]
            ]);
            $sheet->getColumnDimension($this->_cellName[$index])->setWidth('20');
        }
        $rowIndex = 2;
        $reconciliationList = (new SsyReconciliationOrderTable())->whereBetween('recon_time', ['2025-01', '2025-09'])->where('status', 1)
            ->orderBy('recon_time', 'asc')->get()->toArray();
        $subjects = array_column(config("scm.subject"), "brand_code_s", "supplier_id");
        foreach ($reconciliationList as $reconItem){
            $purchaseinIds = array_map(function ($item) {return (int)$item;}, unserialize($reconItem['purchasein_ids']));
            $returnsList = (new SsyJstPurchaseinOrderEmbroideryCountTable())->whereIn('id', $purchaseinIds)->orderBy('id', 'asc')->get()->toArray();
            $total = count($returnsList);
            foreach ($returnsList as $index => $returnItem){
                echo "正在写入: {$reconItem['recon_time']} {$reconItem['factory_name']} [{$total}, ".($index+1)
                    ."] {$returnItem['processing_code']} {$returnItem['type_no']} \n";
                $examineObj = (new SsyPricingExamineTable())->where('processing_code', $returnItem['processing_code'])->first(['pay_pricing_number'])->toArray();
                $verifyPriceObj = (new VerifyPriceTable())->where('number', $examineObj['pay_pricing_number'])->first()->toArray();
                $data = [
                    'brand_name' =>  $subjects[$reconItem['source_factory_groups_id']] ?? $reconItem['source_factory_groups_id'],
                    'recon_time' => $reconItem['recon_time'],
                    'factory_nmae' => $reconItem['factory_name'],
                    'type' => $reconItem['type'] == 0 ? '成衣' : '绣花',
                    'purchasein_amount' => $reconItem['purchasein_amount'],
                    'additional_amount' => $reconItem['additional_amount'],
                    'fine_amount' => $reconItem['fine_amount'],
                    'kaip_amount' => $reconItem['kaip_amount'],
                    'pay_amount' => $reconItem['pay_amount'],
                    'remark' => $reconItem['remark'],
                    'processing_code' => $returnItem['processing_code'],
                    'type_no' => $returnItem['type_no'],
                    'type_name' => $returnItem['type_name'],
                    'totalnum' => $returnItem['totalnum'],
                    'pay_machining_price' => $returnItem['pay_machining_price'],
                    'total_cost_amount' => $returnItem['total_cost_amount'],
                    'emb_billing_amount' => $returnItem['emb_billing_amount'],
                    'pay_price' => $returnItem['pay_price'],
                    'cost_amount' => $returnItem['cost_amount'],
                    'billing_amount' => $returnItem['billing_amount'],
                    'verify_price_number' => $verifyPriceObj['number'],
                    'f69' => (Double)$verifyPriceObj['f69'],
                    'f70' => (Double)$verifyPriceObj['f70'],
                    'f71' => (Double)$verifyPriceObj['f71'],
                    'f72' => (Double)$verifyPriceObj['f72'],
                    'f77' => (Double)$verifyPriceObj['f77'],
                    'f78' => (Double)$verifyPriceObj['f78'],
                    'f61' => (Double)$verifyPriceObj['f61'],
                    'f62' => (Double)$verifyPriceObj['f62'],
                    'f63' => (Double)$verifyPriceObj['f63'],
                    'f64' => (Double)$verifyPriceObj['f64'],
                    'f65' => (Double)$verifyPriceObj['f65'],
                ];
                foreach ($header as $hIndex => $hItem){
                    $sheet->setCellValue($this->_cellName[$hIndex].$rowIndex, $data[$hItem[0]]);
                }
                $rowIndex++;
            }
        }
        // 保存Excel文件
        (new Xlsx($spreadsheet))->save($file);
        die("处理结束！！！");
    }

    //同步出库数据结构
    public function syncDelivery()
    {
        $start = '2025-08-26 00:00:00';
        $end = date('Y-m-d 23:59:59', strtotime("+ 6 days".$start));
        while(true) {
            if ($start > date('Y-m-d 00:00:00')) {
                die();
            }
            $list = (new SsyProcessingListDetailsDeliveryLogBakTable())->whereBetween('createtime', [$start, $end])->orderBy('createtime', 'asc')->get()->toArray();
            foreach ($list as $index => $item){
                try{
                    $numbers = unserialize($item['numberarr']);
                    if(isset($numbers[0]['number'])){
                        foreach($numbers as $number){
                            $exist = (new SsyProcessingListDetailsDeliveryLogTable())->where('courier_number', $item['courier_number'])
                                ->where('number', $number['number'])->exists();
                            if($exist){
                                continue;
                            }
                            (new SsyProcessingListDetailsDeliveryLogTable())->createData([
                                'courier_number' => $item['courier_number'],
                                'number' => $number['number'],
                                'createtime' => $item['createtime']
                            ]);
                        }
                    }else{
                        $exist = (new SsyProcessingListDetailsDeliveryLogTable())->where('courier_number', $item['courier_number'])->whereNull('number')->exists();
                        if($exist){
                            continue;
                        }
                        (new SsyProcessingListDetailsDeliveryLogTable())->createData([
                            'courier_number' => $item['courier_number'],
                            'createtime' => $item['createtime']
                        ]);
                    }
                    echo "获取时间：{$start}  {$end} 总计：".count($list)." 执行：".($index+1)."\n";
                }catch (\Exception $e){
                    die($e->getMessage().json_encode($item));
                }
            }
            $start = date('Y-m-d 00:00:00', strtotime("+ 7 days" . $start));
            $end = date('Y-m-d 23:59:59', strtotime("+ 7 days". $end));
        }
    }

    //优化工艺单表字段
    public function optimizeGY()
    {
        $list = (new SsyNewProductProcessSheetTable())->orderBy('id', 'asc')->get()->toArray();
        foreach ($list as $index => $item){
            echo "总计：".count($list)." 执行：".($index+1)."\n";
            $data = [];
            if(!empty($item['production_sewing_process_requirements'])){
                $data['production_sewing_process_requirements'] = json_encode(unserialize($item['production_sewing_process_requirements']), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['detail_drawing'])){
                $imgs = unserialize($item['detail_drawing']);
                $data['detail_drawing'] = json_encode(array_column($imgs, 'url'), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['process_instruction'])){
                $data['process_instruction'] = json_encode(unserialize($item['process_instruction']), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['mark_position'])){
                $data['mark_position'] = json_encode(unserialize($item['mark_position']), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['requirements_for_locking_nails'])){
                $data['requirements_for_locking_nails'] = json_encode(unserialize($item['requirements_for_locking_nails']), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['special_process_requirements'])){
                $data['special_process_requirements'] = json_encode(unserialize($item['special_process_requirements']), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['packaging_specification_requirements'])){
                $data['packaging_specification_requirements'] = json_encode(unserialize($item['packaging_specification_requirements']), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['cutting_requirements'])){
                $data['cutting_requirements'] = unserialize($item['cutting_requirements']);
            }
            if(!empty($item['subsequent_process'])){
                $data['subsequent_process'] = unserialize($item['subsequent_process']);
            }
            if(!empty($item['acceptance_criteria'])){
                $data['acceptance_criteria'] = unserialize($item['acceptance_criteria']);
            }
            (new SsyNewProductProcessSheetTable())->updateData($item['id'], $data);
        }
    }

    //优化尺寸表字段
    public function optimizeSize()
    {
        $list = (new SsyNewProductsTable())->orderBy('id', 'asc')->get()->toArray();
        foreach ($list as $index => $item){
            echo "总计：".count($list)." 执行：".($index+1)."\n";
            if(!empty($item['wear_image'])){
                $item['wear_image'] = json_encode(unserialize($item['wear_image']), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['measure_image'])){
                $item['measure_image'] = json_encode(unserialize($item['measure_image']), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['plank_house_table_title'])){
                $item['plank_house_table_title'] = json_encode(unserialize($item['plank_house_table_title']), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['plank_house_table_data'])){
                $item['plank_house_table_data'] = json_encode(unserialize($item['plank_house_table_data']), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['products_base_cdoe'])){
                $item['products_base_cdoe'] = json_encode(unserialize($item['products_base_cdoe']), JSON_UNESCAPED_UNICODE);
            }
            if(!empty($item['specifications_base_cdoe'])){
                $item['specifications_base_cdoe'] = json_encode(unserialize($item['specifications_base_cdoe']), JSON_UNESCAPED_UNICODE);
            }
            $data = [
                "type_no" => $item['type_no'],
                "type_name" => $item['type_name'],
                "publisher" => $item['publisher'],
                "wear_image" => $item['wear_image'],
                "measure_image" => $item['measure_image'],
                "be_careful" => $item['be_careful'],
                "reminder" => $item['reminder'],
                "risk" => $item['risk'],
                "modify_comments" => $item['sample_clothes_modification_comments'],
                "plank_house_table_title" => $item['plank_house_table_title'],
                "plank_house_table_data" => $item['plank_house_table_data'],
                "products_base_cdoe" => $item['products_base_cdoe'],
                "specifications_base_cdoe" => $item['specifications_base_cdoe'],
                "size_code_status" => $item['size_code_status'],
                "process_sheet_status" => $item['process_sheet_status'],
                "sealed_status" => $item['sealed_status'],
                "createtime" => $item['createtime']
            ];
            $exist = (new SsyNewProductsSizeTable())->where('type_no', $data['type_no'])->first();
            if(!empty($exist)){
                (new SsyNewProductsSizeTable())->updateData($exist->id, $data);
            }else{
                (new SsyNewProductsSizeTable())->createData($data);
            }
        }
    }

    //拉取领猫款式信息
    public function pullStyleNoLM()
    {
        $start = '2023-11-23 00:00:00';
        $end = date('Y-m-d 23:59:59', strtotime("+ 6 days".$start));
        while(true){
            if($start > date('Y-m-d 00:00:00')){
                die();
            }
            echo "获取时间：{$start}  {$end} ";
            for($page = 1; $page <= 1; $page++){
                $res = (new LinmaoRepository())->getProduct(['page' => $page, 'size' => 100, 'modifiedBegin' => $start, 'modifiedEnd' => $end]);
                $this->setStyleData($res['data']['datas'] ?? []);
                if($page == $res['data']['pageCount']){
                    break;
                }
            }
            echo "搜索页数: ".$res['data']['pageCount']." 总计：".$res['data']['totalCount']."\n";
            $start = date('Y-m-d 00:00:00', strtotime("+ 7 days" . $start));
            $end = date('Y-m-d 23:59:59', strtotime("+ 7 days". $end));
        }
    }

    public function setStyleData($list)
    {
        $seasonId = ["春" => 1, "夏" => 2, "秋" => 3, "冬" => 4];
        $seasonMap = ["春第一波" => 3, "春第二波" => 4, "春第三波" => 5, "夏第一波" => 6, "夏第二波" => 7, "夏第三波" => 8,
            "秋第一波" => 9, "秋第二波" => 10, "秋第三波" => 11, "冬第一波" => 12, "冬第二波" => 1, "冬第三波" => 2];
        foreach ($list as $item){
            if($item['isDisable']){
                continue;
            }
            $skus = $item['skus'] ?? [];
            $sizeList = [];
            $isSingleColour = true;//是否单色专用
            foreach ($skus as $index => $skuObj) {
                $sizeList[] = [
                    'position' => $index+1,
                    'size_id' => 0,
                    'size_number' => $skuObj['sizeCode'],
                    'size' => $skuObj['sizeCode'],
                    'is_product' => 1
                ];
                //判断颜色码是否写入sku
                if(str_starts_with($skuObj['skuCode'], $item['pdtCode'].$skuObj['colorCode'])){
                    $isSingleColour = false;
                }
            }
            try{
                $data = [
                    'number' => $item['pdtCode'],
                    't17_id' => 0,
                    'name' => $item['pdtName'],
                    'short_name' => $item['ctgName'],
                    'type_id' => 1,
                    'product_category_id' => 6,
                    'product_category' => "汉元素",
                    'detail_category_id' => 40,
                    'detail_category' => "其他",
                    'designer_id' => 0,
                    'designer' => $item['createUser'],
                    'f3_id' => 0,
                    'f3' => $item['designer'],
                    'paper_designer_id' => 0,
                    'paper_designer' => "",
                    'year' => (Int)$item['yearName'],
                    'month' => $seasonMap[$item['bandName']],
                    'season_id' => $seasonId[$item['seasonName']],
                    'season' => $item['seasonName'],
                    'brand_id' => 6,
                    'brand' => "七月夕",
                    'target_id' => 1,
                    'target' => "女装",
                    't1_id' => 1,
                    't1' => "新汉服",
                    'composition' => "",
                    'f79' => "",
                    't5' => "",
                    't6' => "",
                    'f7' => "",
                    'f8_id' => 0,
                    'f8_short' => "",
                    'f9_id' => 0,
                    'f9_short' => "",
                    'f10_id' => 0,
                    'f10_short' => "",
                    'f11_id' => 0,
                    'f11_short' => "",
                    'f12_id' => 0,
                    'f12_short' => "",
                    'f12' => "",
                    'f13' => 0,
                    'f14' => 0,
                    'f15' => 0,
                    'f19' => 0,
                    'f20' => 0,
                    'f21' => 0,
                    'comment' => "",
                    'f36' => "",
                    'approval_state' => 0,
                    'state' => 0,
                    'creator_id' => 0,
                    'creator' => $item['createUser'],
                    'creation_time' => strtotime(date('Y-m-d', strtotime($item['createTime']))) - 1512460800,
                    'style_size_id' => 0,
                    'embroider_designer_id' => 0,
                    'embroider_designer' => ""
                ];
                $exist = (new StyleTable())->where('number', $data['number'])->exists();
                if($exist){
                    continue;
                }
                DB::connection("mysql_sj")->beginTransaction();
                $styleRes = (new StyleTable())->createData($data);
                if($styleRes['code'] !== 0){
                    DB::connection("mysql_sj")->rollBack();
                    continue;
                }
                $styleId = $styleRes['id'];
                foreach ($sizeList as $sizeObj){
                    $sizeObj['style_id'] = $styleId;
                    (new StyleSizeTable())->createData($sizeObj);
                }
                if($isSingleColour){
                    (new StyleColourTable())->createData([
                        'style_id' => $styleId,
                        'position' => 1,
                        'colour_id' => 23,
                        'colour_number' => "",
                        'colour' => '单色专用',
                        'colour_value' => 16775416,
                        'is_product' => 1
                    ]);
                }else{
                    foreach ($item['skcs'] as $index => $skcObj) {
                        $colourName = str_replace("色", "", $skcObj['colorName']);
                        $colourObj = (new StyleColourTable())->where('colour', $colourName)->orderBy('id', 'asc')->first();
                        if(empty($colourObj)){
                            $colourObj = (new StyleColourTable())->where('colour', 'like', '%'.$colourName.'%')
                                ->orderBy('id', 'asc')->first();
                        }
                        $colourValue = $colourObj->colour_value ?? 0;
                        (new StyleColourTable())->createData([
                            'style_id' => $styleId,
                            'position' => $index+1,
                            'colour_id' => $colourObj->colour_id ?? 0,
                            'colour_number' => $skcObj['colorCode'],
                            'colour' => $skcObj['colorName'],
                            'colour_value' => $colourValue,
                            'is_product' => 1
                        ]);
                    }
                }
                DB::connection("mysql_sj")->commit();
                //保存款式图片
                $imageExist = (new SsyStyleImagesTable())->where('type_no', $data['number'])->exists();
                if(!$imageExist){
                    $fileName = $data['number']."_".date('His');
                    $fileRes = CommonRepository::uploadCDN($item['imgUrl'], 'style', $fileName);
                    if($fileRes['file'] ?? ""){
                        (new SsyStyleImagesTable())->createData([
                            'type_no' => $data['number'],
                            'createtime' => date('Y-m-d H:i:s'),
                            'images' => $fileRes['file'],
                            'thumb_images' => $fileRes['file'],
                            'images_list' => json_encode([$fileRes['file']]),
                            'thumb_images_list' => json_encode([$fileRes['file']])
                        ]);
                    }
                }
            }catch (\Exception $e){
                DB::connection("mysql_sj")->rollBack();
            }
        }
    }

    //拉取领猫款式的物料清单
    public function pullStyleMaterielLM()
    {
        $styleList = (new StyleTable())->where('brand_id', 6)->get(['id', 'number', 'name', 'paper_designer'])->toArray();
        foreach ($styleList as $style){
            $materielRes = (new LinmaoRepository())->getProductMaterial(['page' => 1, 'size' => 100, 'codes' => $style['number']]);
            if(!isset($materielRes['data']['datas']) || empty($materielRes['data']['datas'])){
                echo "-------没有发现物料清单: 款号: ".$style['number']."\n";
                continue;
            }
            $styleBomExits = (new StyleBomTable())->where('style_id', $style['id'])->exists();
            if($styleBomExits){
                echo "*******物料清单已导入过: 款号: ".$style['number']."\n";
                continue;
            }
            //获取核价清单
            $priceRes = (new LinmaoRepository())->getProductPrice(['page' => 1, 'size' => 100, 'codes' => $style['number']]);
            $prices = $priceRes['data']['datas'][0]['fees'] ?? [];
            $priceMap = [];
            foreach ($prices as $obj){
                $priceMap[$obj['mtCode']] = ['amount' => $obj['useAmt'], 'price' => $obj['price'] * 1.1, 'color' => $obj['colorInfo'] ?? ""];
            }
            $skuCode = $materielRes['data']['datas'][0]['skuCode'];
            $materiels = array_reverse(array_filter($materielRes['data']['datas'], function($obj) use($skuCode){return $obj['skuCode'] == $skuCode;}));
            echo "开始导入物料清单: 款号: ".$style['number']." 共计物料: ".count($materiels)."条\n";
            try{
                DB::connection("mysql_sj")->beginTransaction();
                foreach ($materiels as $index => $obj) {
                    $materielObj = (new MaterielTable())->where('number', $obj['mtCode'])->first();
                    if(empty($materielObj)){
                        continue;
                    }
                    $materielCategoryObj = (new MaterielCategoryTable())->where('id', $materielObj->materiel_category_id)->first();
                    $materielMajorCategoryId = $materielCategoryObj->materiel_major_category_id ?? 1;
                    $materielMajorCategory = CommonRepository::CATEGORY[$materielMajorCategoryId];
                    $unitObj = (new UnitTable())->where('id', $materielObj->materiel_major_unit_id)->first();
                    $data = [
                        'style_id' => $style['id'],
                        'position' => $index+1,
                        'type' => 3,
                        'materiel_id' => $materielObj->id,
                        'materiel_number' => $materielObj->number,
                        'materiel' => $materielObj->name,
                        'materiel_major_category_id' => $materielMajorCategoryId,
                        'materiel_major_category' => $materielMajorCategory,
                        'materiel_minor_category_id' => $materielCategoryObj->id ?? 0,
                        'materiel_minor_category' => $materielCategoryObj->name ?? "",
                        'materiel_major_unit_id' => $unitObj->id,
                        'materiel_major_unit' => $unitObj->name,
                        'materiel_attribute_id' => $materielObj->materiel_attribute_id,
                        'materiel_attribute' => $materielObj->materiel_attribute,
                        'part' => $obj['usePart'],
                        'is_multiple_colour' => 0,
                        'confirm' => 1,
                        'comment' => $obj['mtComponent'] ?? "",
                        'f35' => "",
                        'supplier_id' => $materielObj->id,
                        'supplier' => $materielObj->supplier ?: "",
                        'supplier_contact_name' => $materielObj->supplier_contact_name ?: "",
                        'supplier_phone' => trim($materielObj->supplier_phone ?: ""),
                        'supplier_address' => trim($materielObj->supplier_address ?: ""),
                        'price' => $priceMap[$obj['mtCode']]['price'] ?? 0,
                        'is_product' => 0
                    ];
                    $styleBomRes = (new StyleBomTable())->createData($data);
                    if($styleBomRes['code'] !== 0){
                        DB::connection("mysql_sj")->rollBack();
                        continue;
                    }
                    //用料详情（单耗）
                    $bomSizeConfig = [
                        'style_id' => $style['id'],
                        'style_bom_id' => $styleBomRes['id'],
                        'amount' => $priceMap[$obj['mtCode']]['amount'] ?? 0,
                        'content' => json_encode([], JSON_UNESCAPED_UNICODE),
                        'sr' => "",
                        'is_product' => 0
                    ];
                    (new StyleBomSizeConfigTable())->createData($bomSizeConfig);
                    //物料颜色
                    $colourContent = !empty($obj['colorCode']) && !empty($obj['colorName']) ? "[{$obj['colorCode']}]{$obj['colorName']}" : "";
                    $colourContent = isset($priceMap[$obj['mtCode']]['color']) && !empty($priceMap[$obj['mtCode']]['color']) ? $priceMap[$obj['mtCode']]['color']
                        : $colourContent;
                    $colourList = (new StyleColourTable())->where('style_id', $style['id'])->get()->toArray();
                    foreach ($colourList as $colourObj){
                        $colourData = [
                            'style_id' => $style['id'],
                            'style_bom_id' => $styleBomRes['id'],
                            'style_colour_id' => $colourObj['id'],
                            'content' => json_encode(empty($colourContent) ? [] :
                                [["code" => 16777215, "name" => "颜色", "value" => $colourContent, "change" => false]] , JSON_UNESCAPED_UNICODE),
                            'is_product' => 0
                        ];
                        (new StyleBomColourConfigTable())->createData($colourData);
                    }
                }
                DB::connection("mysql_sj")->commit();
            }catch (\Exception $e){
                DB::connection("mysql_sj")->rollBack();
            }
            //同步上新表
            $exist = (new SsyNewProductsSizeTable())->where('type_no', $style['number'])->exists();
            if($exist){
                continue;
            }
            $data = [
                "type_no" => $style['number'],//款号
                "type_name" => $style['name'],//款名
                "publisher" => $style['paper_designer'],//版师
                "createtime" => date('Y-m-d H:i:s'),
            ];
            (new SsyNewProductsSizeTable())->createData($data);
        }
    }

    //拉取领猫物料档案信息
    public function pullMaterielLM()
    {
        $category = [
            "赠品打底裤" => [
                "面料" => ["主料", "梭织面料"],
                "辅料" => ["辅料", "其他"]
            ],
            "静电刷" => [
                "辅料" => ["辅料", "其他"]
            ],
            "气泡袋" => [
                "辅料" => ["特殊工艺", "气泡袋"]
            ],
            "彩色衬板" => [
                "辅料" => ["辅料", "衬"]
            ],
            "吊粒" => [
                "辅料" => ["辅料", "吊粒"]
            ],
            "七月夕定制子母扣/七月夕免手缝对扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "合格证二维码不干胶" => [
                "辅料" => ["特殊工艺", "贴纸"]
            ],
            "碳带" => [
                "辅料" => ["辅料", "其他"]
            ],
            "小红书优质买家秀征集卡片/退换货服务详情卡/淘宝活动卡片/抖音活动卡片/国风课堂小册子" => [
                "辅料" => ["辅料", "其他"]
            ],
            "水洗/水洗唛" => [
                "面料工艺" => ["特殊工艺", "洗水"],
                "辅料" => ["辅料", "主标"]
            ],
            "语裳入梦飞机盒/飞机盒手拎包装袋" => [
                "辅料" => ["特殊工艺", "纸箱"]
            ],
            "透明新包装袋" => [
                "辅料" => ["特殊工艺", "胶袋"]
            ],
            "雪尼尔" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "透明TPU" => [
                "面料" => ["主料", "毛皮和皮革"]
            ],
            "莱赛尔" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "绗棉" => [
                "辅料" => ["特殊工艺", "绗棉"],
                "面料" => ["特殊工艺", "绗棉"],
                "面料工艺" => ["特殊工艺", "绗棉"]
            ],
            "羊毛混纺" => [
                "面料" => ["主料", "针织面料"]
            ],
            "棉混纺" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "真丝" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "苎麻面料" => [
                "面料" => ["主料", "针织面料"]
            ],
            "人丝混纺" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "亚麻" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "人棉" => [
                "面料" => ["主料", "梭织面料"],
                "里料" => ["主料", "梭织面料"]
            ],
            "竹纤维混纺" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "防晒" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "缎面" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "仿醋酸" => [
                "面料" => ["主料", "针织面料"]
            ],
            "醋酸" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "天丝混纺" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "网纱" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "欧根纱" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "黏胶梭织" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "皮革" => [
                "面料" => ["主料", "毛皮和皮革"]
            ],
            "呢料" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "全棉梭织" => [
                "面料" => ["主料", "梭织面料"],
                "面料工艺" => ["主料", "梭织面料"]
            ],
            "涤纶梭织" => [
                "面料" => ["主料", "梭织面料"],
                "里料" => ["主料", "梭织面料"],
                "辅料" => ["辅料", "配饰"]
            ],
            "丝绒面料" => [
                "面料" => ["主料", "梭织面料"],
            ],
            "雪纺" => [
                "面料" => ["主料", "梭织面料"],
            ],
            "蕾丝" => [
                "面料" => ["主料", "梭织面料"],
                "辅料" => ["辅料", "花边"]
            ],
            "牛仔" => [
                "面料" => ["主料", "梭织面料"],
            ],
            "棉麻" => [
                "面料" => ["主料", "梭织面料"],
            ],
            "灯芯绒" => [
                "面料" => ["主料", "梭织面料"],
            ],
            "网布" => [
                "面料" => ["主料", "梭织面料"],
                "辅料" => ["辅料", "其他"],
                "里料" => ["辅料", "其他"]
            ],
            "丝绒" => [
                "面料" => ["主料", "梭织面料"],
                "里料" => ["辅料", "其他"]
            ],
            "羊羔毛" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "兔毛" => [
                "面料" => ["主料", "梭织面料"],
                "里料" => ["辅料", "其他"]
            ],
            "毛绒" => [
                "面料" => ["主料", "梭织面料"],
                "里料" => ["辅料", "其他"],
                "面料工艺" => ["辅料", "其他"],
                "辅料" => ["辅料", "其他"]
            ],
            "TR" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "尼龙" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "针织净色" => [
                "面料" => ["主料", "针织面料"],
                "面料工艺" => ["主料", "针织面料"]
            ],
            "针织花色" => [
                "面料" => ["主料", "针织面料"],
                "辅料" => ["辅料", "其他"],
                "面料工艺" => ["主料", "针织面料"]
            ],
            "针织条纹" => [
                "面料" => ["主料", "针织面料"]
            ],
            "卫衣棉" => [
                "面料" => ["主料", "针织面料"]
            ],
            "莫代尔棉" => [
                "面料" => ["主料", "针织面料"]
            ],
            "针织里" => [
                "面料" => ["主料", "针织面料"]
            ],
            "精棉里" => [
                "面料" => ["主料", "针织面料"]
            ],
            "雪纺里布" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "色丁里布" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "人造丝" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "天丝棉四面弹" => [
                "面料" => ["主料", "梭织面料"],
                "里料" => ["主料", "梭织面料"]
            ],
            "仿人丝" => [
                "面料" => ["主料", "梭织面料"]
            ],
            "毛领" => [
                "面料" => ["主料", "毛皮和皮革"],
                "辅料" => ["主料", "毛皮和皮革"],
                "面料工艺" => ["主料", "毛皮和皮革"]
            ],
            "实木衣架/衣架罩" => [
                "辅料" => ["特殊工艺", "衣架"]
            ],
            "合格证贴纸/条形码贴纸3*6CM" => [
                "辅料" => ["特殊工艺", "贴纸"]
            ],
            "棉布袋" => [
                "辅料" => ["辅料", "其他"]
            ],
            "合格证吊牌" => [
                "辅料" => ["特殊工艺", "贴纸"]
            ],
            "领标（logo）/双面呢大领标" => [
                "辅料" => ["辅料", "其他"]
            ],
            "防伪扣" => [
                "辅料" => ["辅料", "其他"]
            ],
            "吊牌/布吊牌" => [
                "辅料" => ["辅料", "吊牌"]
            ],
            "吊绳" => [
                "辅料" => ["辅料", "绳带"]
            ],
            "尺码标" => [
                "辅料" => ["辅料", "尺码标"]
            ],
            "扇骨" => [
                "辅料" => ["辅料", "其他"]
            ],
            "填充棉" => [
                "辅料" => ["辅料", "其他"]
            ],
            "毛球" => [
                "辅料" => ["辅料", "其他"]
            ],
            "毛条" => [
                "辅料" => ["辅料", "其他"]
            ],
            "帽子" => [
                "辅料" => ["辅料", "其他"]
            ],
            "仿真花/永生花/干花" => [
                "辅料" => ["辅料", "其他"]
            ],
            "鱼骨" => [
                "辅料" => ["辅料", "其他"]
            ],
            "球针" => [
                "辅料" => ["辅料", "其他"]
            ],
            "金属辅料" => [
                "辅料" => ["辅料", "其他"]
            ],
            "衬布" => [
                "辅料" => ["辅料", "衬"]
            ],
            "木棒" => [
                "辅料" => ["辅料", "其他"]
            ],
            "伸缩易拉扣" => [
                "辅料" => ["辅料", "其他"]
            ],
            "尼龙拉链" => [
                "辅料" => ["辅料", "拉链"]
            ],
            "金属拉链" => [
                "辅料" => ["辅料", "拉链"]
            ],
            "树脂拉链" => [
                "辅料" => ["辅料", "拉链"]
            ],
            "隐形拉链" => [
                "辅料" => ["辅料", "拉链"]
            ],
            "链条" => [
                "辅料" => ["辅料", "拉链"]
            ],
            "贝壳扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "压襟扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "盘扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "子母扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "花型扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "花托" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "吊坠" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "吊坠花片" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "开口圈" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "龙虾扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "铃铛" => [
                "辅料" => ["辅料", "铃铛"]
            ],
            "隔珠" => [
                "辅料" => ["辅料", "装饰珠子"]
            ],
            "异形珠" => [
                "面料" => ["辅料", "装饰珠子"],
                "辅料" => ["辅料", "装饰珠子"]
            ],
            "圆珠" => [
                "辅料" => ["辅料", "装饰珠子"]
            ],
            "备扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "珠子" => [
                "面料" => ["辅料", "装饰珠子"],
                "辅料" => ["辅料", "装饰珠子"]
            ],
            "珍珠蘑菇扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "摇头扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "工字扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "衬衫扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "暗扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "四合扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "金属扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "日字扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "裤钩" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "葫芦扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "大衣扣" => [
                "面料" => ["辅料", "纽扣"],
                "辅料" => ["辅料", "纽扣"]
            ],
            "蘑菇扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "包扣" => [
                "辅料" => ["辅料", "纽扣"],
                "辅料工艺" => ["辅料", "纽扣"]
            ],
            "调节扣" => [
                "辅料" => ["辅料", "纽扣"],
                "辅料工艺" => ["辅料", "纽扣"]
            ],
            "树脂扣" => [
                "辅料" => ["辅料", "纽扣"],
                "面料" => ["辅料", "纽扣"]
            ],
            "别针" => [
                "辅料" => ["辅料", "其他"]
            ],
            "珍珠" => [
                "辅料" => ["辅料", "串珠"]
            ],
            "鸡眼" => [
                "辅料" => ["辅料", "其他"]
            ],
            "猪鼻扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "牛角扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "钩扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "魔术贴" => [
                "辅料" => ["辅料", "其他"]
            ],
            "旗袍扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "斜孔珠扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "袖扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "气眼暗扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "插扣" => [
                "辅料" => ["辅料", "纽扣"]
            ],
            "定做罗纹" => [
                "辅料" => ["辅料", "其他"]
            ],
            "珠链" => [
                "辅料" => ["辅料", "串珠"]
            ],
            "绣花线" => [
                "辅料" => ["辅料", "绳带"]
            ],
            "玉线" => [
                "辅料" => ["辅料", "绳带"]
            ],
            "橡筋绳" => [
                "辅料" => ["辅料", "橡筋"]
            ],
            "帽绳" => [
                "辅料" => ["辅料", "绳带"]
            ],
            "花边" => [
                "辅料" => ["辅料", "花边"],
                "面料" => ["辅料", "花边"]
            ],
            "腰带" => [
                "辅料" => ["辅料", "绳带"]
            ],
            "织带" => [
                "辅料" => ["辅料", "织带"],
                "面料" => ["辅料", "织带"]
            ],
            "橡筋" => [
                "辅料" => ["辅料", "橡筋"]
            ],
            "蕾丝花边" => [
                "辅料" => ["辅料", "花边"],
                "面料" => ["辅料", "花边"]
            ],
            "流苏" => [
                "辅料" => ["辅料", "流苏"],
                "面料" => ["辅料", "流苏"]
            ],
            "蝴蝶结" => [
                "辅料" => ["辅料", "蝴蝶结"]
            ],
            "拉链扣绳" => [
                "辅料" => ["辅料", "绳带"]
            ],
            "毛线" => [
                "辅料" => ["辅料", "绳带"]
            ],
            "编绳" => [
                "辅料" => ["辅料", "绳带"]
            ],
            "藤编球" => [
                "辅料" => ["辅料", "其他"]
            ],
            "平纹带" => [
                "辅料" => ["辅料", "其他"]
            ],
            "扁绳" => [
                "辅料" => ["辅料", "绳带"]
            ],
            "圆绳" => [
                "辅料" => ["辅料", "绳带"]
            ],
            "蝴蝶结" => [
                "辅料" => ["辅料", "蝴蝶结"]
            ],
            "炒色" => [
                "面料" => ["辅料", "印花"]
            ],
            "扎染" => [
                "面料" => ["辅料", "印花"]
            ],
            "成品印花" => [
                "面料" => ["辅料", "印花"]
            ],
            "织金" => [
                "面料" => ["辅料", "印花"]
            ],
            "提花" => [
                "辅料" => ["辅料", "印花"],
                "面料" => ["辅料", "印花"]
            ],
            "植绒" => [
                "面料" => ["辅料", "植绒"]
            ],
            "烫金" => [
                "面料" => ["辅料", "烫金"],
                "面料工艺" => ["辅料", "烫金"]
            ],
            "轧花" => [
                "面料工艺" => ["辅料", "印花"],
                "面料" => ["辅料", "印花"]
            ],
            "印花" => [
                "面料" => ["辅料", "印花"],
                "面料工艺" => ["辅料", "印花"]
            ],
            "绣花" => [
                "面料" => ["辅料", "绣花"],
                "辅料" => ["辅料", "绣花"],
                "面料工艺" => ["辅料", "绣花"]
            ],
            "洗水" => [
                "面料工艺" => ["辅料", "绣花"]
            ],
            "染色" => [
                "辅料" => ["特殊工艺", "染色"],
                "面料工艺" => ["特殊工艺", "染色"],
                "辅料工艺" => ["特殊工艺", "染色"]
            ],
            "复合工艺" => [
                "面料" => ["特殊工艺", "复合"],
                "面料工艺" => ["特殊工艺", "复合"]
            ],
            "麂皮" => [
                "面料" => ["辅料", "印花"]
            ],
            "激光雕花" => [
                "面料" => ["辅料", "其他"],
                "辅料工艺" => ["辅料", "其他"],
                "面料工艺" => ["辅料", "其他"]
            ],
            "热缩" => [
                "面料工艺" => ["辅料", "其他"]
            ],
            "牛仔水洗" => [
                "面料工艺" => ["特殊工艺", "洗水"]
            ],
            "石头圆环" => [
                "辅料" => ["辅料", "其他"]
            ]
        ];
        $unitList = (new UnitTable())->get()->toArray();
        $unitMap = array_column($unitList, 'id', 'name');
        $start = '2025-10-15 00:00:00';
        $end = date('Y-m-d 23:59:59', strtotime("+ 6 days".$start));
        while(true){
            if($start > date('Y-m-d 00:00:00')){
                die();
            }
            echo "获取时间：{$start}  {$end} ";
            for($page = 1; $page <= 3; $page++){
                $res = (new LinmaoRepository())->getMaterial(['page' => $page, 'size' => 100, 'modifiedBegin' => $start, 'modifiedEnd' => $end]);
                $this->setMaterielData($res['data']['datas'] ?? [], $category, $unitMap);
                if($page == $res['data']['pageCount']){
                    break;
                }
            }
            echo "搜索页数: ".$res['data']['pageCount']." 总计：".$res['data']['totalCount']."\n";
            $start = date('Y-m-d 00:00:00', strtotime("+ 7 days" . $start));
            $end = date('Y-m-d 23:59:59', strtotime("+ 7 days". $end));
        }
    }

    public function setMaterielData($list, $category, $unitMap)
    {
        foreach ($list as $item){
            $isEnable = $item['isEnable'] ?? 1;
            if($isEnable){
                continue;
            }
            $factoryData = [];
            if($item['supplierCode'] ?? ""){
                $res = (new LinmaoRepository())->getSupplier(['page' => 1, 'size' => 100, 'codes' => $item['supplierCode']]);
                $factoryObj = $res['data']['datas'][0] ?? [];
                $exist = (new SsyProcessingFactoryNameTable())->where('supplier_id', $factoryObj['spCode'] ?? "")->first();
                $factoryData = !empty($exist) ? $exist->toArray() : [];
                if(!empty($factoryObj) && empty($factoryData)){
                    $factoryData = [
                        'supplier_id' => $factoryObj['spCode'],
                        'factory_name' => $factoryObj['spName'],
                        'factory_name_jiancheng' => $factoryObj['spShortName'],
                        'group' => 8,
                        'group_name' => '物料厂',
                        'createtime' => '2025-09-18 00:00:00',
                        'legal_person' => $factoryObj['contact'],
                        'contact_phone' => $factoryObj['telphone'],
                        'contact_address' => $factoryObj['companyAddr']
                    ];
                    $res = (new SsyProcessingFactoryNameTable())->createData($factoryData);
                    $factoryData['id'] = $res['id'] ?? 0;
                }
            }
            $types = $category[$item['mtCtg']][$item['mtType']] ?? [];
            if(empty($types)){
                echo "过滤内容1：".json_encode($item, JSON_UNESCAPED_UNICODE);
                continue;
            }
            $attributeType = ["主料" => 1, "辅料" => 2, "特殊工艺" => 3];
            $materielCategoryObj = (new MaterielCategoryTable())->where('materiel_major_category_id', $attributeType[$types[0]])
                ->where('name', $types[1])->first();
            if(empty($materielCategoryObj)){
                echo "过滤内容2：".json_encode($item, JSON_UNESCAPED_UNICODE);
                continue;
            }
            $materielAttribute = [];
            if($types[0] == '主料'){
                if(!empty($item['width'])){
                    $materielAttribute['2'] = ['name' => '门幅(cm)', 'value' => (Int)(preg_replace("/cm/is", "", $item['width']))];
                }
                if(!empty($item['weight'])){
                    $materielAttribute['5'] = ['name' => '克重', 'value' => $item['weight']];
                }
                if(!empty($item['mtComponent'])){
                    $materielAttribute['6'] = ['name' => '成分', 'value' => $item['mtComponent']];
                }
            }
            $materielData = [
                'number' => $item['mtCode'],
                'name' => $item['mtName'],
                'materiel_major_unit_id' => $unitMap[$item['unit']] ?? 5,//默认：个
                'materiel_minor_unit_id' => $unitMap[$item['unit']] ?? 5,
                'materiel_attribute_id' => $materielCategoryObj->materiel_attribute_id,
                'materiel_attribute' => empty($materielAttribute) ? "{}" : json_encode($materielAttribute, JSON_UNESCAPED_UNICODE),
                'materiel_category_id' => $materielCategoryObj->id,
                'state' => 0,
                'price' => $item['price'],
                'remark' => $item['remark'],
                'supplier_id' => $factoryData['id'] ?? 0,
                'supplier' => $factoryData['factory_name'] ?? "",
                'supplier_contact_name' => $factoryData['legal_person'] ?? "",
                'supplier_phone' => $factoryData['contact_phone'] ?? "",
                'supplier_address' => $factoryData['contact_address'] ?? "",
                'creator_id' => 0,
                'creator' => $item['createUser'],
                'creation_time' => '2025-09-18 00:00:00'
            ];
            $exist = (new MaterielTable())->where('number', $materielData['number'])->first();
            $materialId = $exist->id ?? "";
            if(empty($exist)){
                $res = (new MaterielTable())->createData($materielData);
                $materialId = $res['id'] ?? "";
            }
            //存图片
            if($item['imgUrl'] && $materialId){
                $imageExist = (new SsyMaterialImagesTable())->where('material_id', $materialId)->first();
                if(empty($imageExist)){
                    $resp = CommonRepository::uploadCDN($item['imgUrl'], 'material');
                    $imageData = [
                        'images' => $resp['file'],
                        'material_id' => $materialId,
                        'createtime' => '2025-09-18 00:00:00'
                    ];
                    (new SsyMaterialImagesTable())->createData($imageData);
                }
            }
        }
    }

    public function updateContractDate()
    {
        $list = (new SsyProcessingListTable())->where('f_status', 0)->orderBy("createtime", "asc")->groupBy(["processing_code", "sku_code", "contract_date", "createtime"])
            ->get(["processing_code", "sku_code", "contract_date", "createtime"])->toArray();
        $total = count($list);
        foreach ($list as $index => $item){
            echo "正在执行：".$total." / ".($index+1)." sku：".$item['sku_code'];
            try{
                //同步合同交期
                $days = (strtotime($item['contract_date']) - strtotime(date('Y-m-d'))) / (24*3600);
                if($days > 0){
                    (new SsyJyProductListTable())->updateDataWhere(['product_code' => $item['sku_code']], [
                        'arrivaldate' => $item['contract_date'],
                        'arrivaldate_title' => ((Int)$days)."天发货"
                    ]);
                    echo "已同步: ".$item['contract_date']." ".$days."天发货\n";
                }else{
                    echo "\n";
                }
            }catch (\Exception $e){

            }
        }
    }
}
